<template>
  <div class="purchase-details ">
    <!-- 头部信息 -->
    <div class="header">
      <div class="title">
        {{ detailData.purchaseName || '' }}
        <span class="title-right">/{{detailData.contractName}}</span>
        <div class="tags">
          <el-tag size="small">{{ $dictUtils.getDictLabel("purchase_type", detailData.purchaseType, '-') }}</el-tag>
          <el-tag size="small" type="info" v-if="detailData.department">{{ detailData.department || '' }}</el-tag>
        </div>
      </div>
      <el-button type="primary" plain size="small" icon="el-icon-back" @click="returnToProjectDetails" v-if="cusType!=1">退出</el-button>
    </div>

    <!-- 概览信息 -->
    <div class="overview">
      <div class="overview-item">
        <div class="label">供应商</div>
        <div class="value">{{ detailData.supplier || '暂无' }}</div>
      </div>
      <div class="amount-info">
        <div class="amount-item">
          <div class="label">合同金额</div>
          <div class="value">{{ detailData.contractAmount || '0.00元' }}</div>
        </div>
        <div class="amount-item">
          <div class="label">累计收票金额</div>
          <div class="value">{{ detailData.invoiceSumAmount || '0.00元' }}</div>
        </div>
        <div class="amount-item">
          <div class="label">累计付款</div>
          <div class="value">{{ detailData.paymentSumAmount || '0.00元' }}</div>
        </div>
        <div class="amount-item">
          <div class="label">质保金待支付</div>
          <div class="value">{{ detailData.qualityGuaranteeFund || '0元' }}</div>
        </div>
      </div>
    </div>

    <!-- 标签页导航 -->
    <div class="tab-container">
      <el-tabs v-model="activeTab" type="card" @tab-click="handleTabClick">
        <!-- <el-tab-pane label="招标" name="tender">
          <projectCostService /> -->
          <!-- <div class="tender-content">
            <el-form :model="tenderForm" ref="tenderFormRef" :rules="tenderRules">
            
              <el-row >
                <el-col :span="12">
                  <div class="section">
                    <div class="section-title">招标公告信息</div>
                    <div class="upload-area">
                      <div class="upload-box">
                        <el-form-item label="招标公告" prop="tenderNotice">
                          <file-upload v-model="tenderForm.tenderNotice" :drag='true'>
                            <div class="upload-content">
                              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                              <div class="upload-text">将文件拖到此处，或<el-buttom>点击上传</el-buttom></div>
                              <div class="upload-tip">支持格式：PDF、Word，单个文件不超过10MB</div>
                            </div>
                          </file-upload>
                        </el-form-item>
                      </div>
                      <div class="date-picker">
                        <div class="label">公告发布时间：</div>
                        <el-form-item label="" prop="tenderNoticeTime">
                          <el-date-picker v-model="tenderForm.tenderNoticeTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择日期时间"
                            style="width: 100%" />
                        </el-form-item>
                      </div>
                    </div>
                  </div>
                </el-col>

                <el-col :span="12">
                  <div class="section">
                    <div class="section-title">中标通知书信息</div>
                    <div class="upload-area">
                      <div class="upload-box">
                        <el-form-item label="中标通知书" prop="winBidNotice">
                          <file-upload v-model="tenderForm.winBidNotice" :drag='true'>
                            <div class="upload-content">
                              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                              <div class="upload-text">将文件拖到此处，或<el-buttom>点击上传</el-buttom></div>
                              <div class="upload-tip">支持格式：PDF、Word，单个文件不超过10MB</div>
                            </div>
                          </file-upload>
                          

                        </el-form-item>
                      </div>
                      <div class="flex">
                        <div class="date-picker">
                        <div class="label">中标时间：</div>
                        <el-form-item label="" prop="winBidTime">
                          <el-date-picker v-model="tenderForm.winBidTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择日期时间"
                            style="width: 100%" />
                        </el-form-item>
                      </div>
                      <div class="date-picker">
                        <div class="label">中标单位：</div>
                        <el-form-item label="" prop="companyId">
                          <GridSelect title="选择招标单位" labelName="companyName" labelValue="id" v-model="tenderForm.companyId" :limit="1" :columns="[
                              { prop: 'id', label: '主键' },
                              { prop: 'companyName', label: '单位名称' }
                            ]" :searchs="[
                              { prop: 'id', label: '主键' },
                              { prop: 'companyName', label: '单位名称' }
                            ]" :api="correspondentService">
                          </GridSelect>
                        </el-form-item>
                      </div>
                      <div class="date-picker">
                        <div class="label">中标金额：</div>
                        <el-form-item label="" prop="winBidAmount">
                         <el-input v-model="tenderForm.winBidAmount" />
                        </el-form-item>
                      </div>
                      </div>
       
                    </div>
                  </div>
                </el-col>
              </el-row>

          
              <div class="section  box-border">
                <div class="section-header">
                  <div class="section-title">投标单位信息</div>
                  <el-button type="primary" @click="addBidder">添加投标单位</el-button>
                </div>
                <div class="bidder-form">
                  <el-table :data="tenderForm.purchaseTenderFirmDTOList.filter((item) => item.delFlag !== '1')" border>
                    <el-table-column label="招标单位" prop="company.companyName">
                      <template #default="scope">
                        <el-form-item :prop="'purchaseTenderFirmDTOList.' + scope.$index + '.company.id'"
                          :rules="[{ required: true, message: '请选择招标单位', trigger: 'change' }]">
                          <GridSelect title="选择招标单位" labelName="companyName" labelValue="id" v-model="scope.row.company.id" :limit="1" :columns="[
                              { prop: 'id', label: '主键' },
                              { prop: 'companyName', label: '单位名称' }
                            ]" :searchs="[
                              { prop: 'id', label: '主键' },
                              { prop: 'companyName', label: '单位名称' }
                            ]" :api="correspondentService">
                          </GridSelect>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column label="联系人" prop="contactPerson">
                      <template #default="scope">
                        <el-input v-model="scope.row.contactPerson" placeholder="请填写联系人" />
                      </template>
                    </el-table-column>
                    <el-table-column label="联系电话" prop="contactPhone">
                      <template #default="scope">
                        <el-input v-model="scope.row.contactPhone" placeholder="请填写联系电话" />
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="100" align="center">
                      <template #default="scope">
                        <el-button type="text" @click="removeBidder(scope.row)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>

       
              <div class="form-footer">
                <el-button type="primary" @click="submitTenderForm" style="width: 100px;">保存</el-button>
              </div> -->
            <!-- </el-form>
          </div> -->
        <!-- </el-tab-pane> -->
        <el-tab-pane label="验收" name="acceptance">
          <PurchaseAcceptanceList />
        </el-tab-pane>
        <el-tab-pane label="收票" name="invoice">
          <PurchaseReceiptList />
        </el-tab-pane>
        <el-tab-pane label="付款" name="payment">
          <PurchasePaymentList ref="paymentList" />
        </el-tab-pane>
        <el-tab-pane label="质保金" name="deposit">
          <PurchaseDepositList />
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import { computed } from "vue"
import PurchaseAcceptanceList from "../acceptance/PurchaseAcceptanceList"
import PurchaseReceiptList from "../receipt/PurchaseReceiptList"
import PurchasePaymentList from "../purchasepayment/PurchasePaymentList"
import PurchaseDepositList from "../deposit/PurchaseDepositList"
import GridSelect from '@/components/gridSelect'
// import FileUpload from '@/components/fileUpload'
import purchaseTenderService from '@/api/tender/purchaseTenderService'
import correspondentService from '@/api/correspondent/correspondentService'
import contractService from '@/api/contract/tPurchaseContractService'
import purchaseReceiptService from '@/api/receipt/purchaseReceiptService'
import projectCostService from '../tender/PurchaseTenderList'
export default {
  name: 'PurchaseDetails',
  provide() {
    return {
      contractId: computed(() => this.contractId),
      purchaseId: computed(() => this.purchaseId),
      projectId: computed(() => this.projectId),
    }
  },
  props:{
    purchaseId:{
      type: String,
			default:'',
    },
    contractNewId:{
      type: String,
			default:'',
    },
    projectId:{
      type: String,
			default:'',
    },
    cusType:{
      type: String,
			default:'',
    }
  },
  data() {
    return {
      contractId: '',
      purchaseId: '',
      projectId: '',
      detailData: {},
      activeTab: 'acceptance',
      tenderDate: '',
      winBidDate: '',
      bidderList: [],
      tenderForm: {
        id: '',
        contract: {
          id: ''
        },
        tenderNoticeTime: '',
        tenderNotice: '',
        winBidTime: '',
        winBidNotice: '',
        purchaseTenderFirmDTOList: []
      },
      tenderRules: {
        tenderNoticeTime: [
          { required: true, message: '请选择公告发布时间', trigger: 'change' }
        ],
        tenderNotice: [
          { required: true, message: '请上传招标公告', trigger: 'change' }
        ],
        winBidTime: [
          { required: true, message: '请选择中标时间', trigger: 'change' }
        ],
        winBidNotice: [
          { required: true, message: '请上传中标通知书', trigger: 'change' }
        ]
      },
      correspondentService: correspondentService,
      paymentDialogVisible: false,
      paymentPlanData: [],
      paymentEditMode: false
    }
  },
  components: {
    PurchaseAcceptanceList,
    PurchaseReceiptList,
    PurchasePaymentList,
    PurchaseDepositList,
    GridSelect,
    projectCostService
  },
  created() {
    this.contractId = this.contractNewId?this.contractNewId:this.$route.query.id
    this.purchaseId = this.$route.query.purchaseId?this.$route.query.purchaseId:this.purchaseId
    this.projectId = this.$route.query.projectId?this.$route.query.projectId:this.projectId

    console.log( this.contractId,this.purchaseId ,this.projectId)
    if (this.contractId) {
      // this.loadTenderData()
      this.getInfo()
    }
  },
  watch: {
    '$route.query': {
      handler(newQuery) {
        this.contractId = newQuery.id;
        this.getInfo()
        // this.loadTenderData()
      },
      immediate: true
    }
  },
  methods: {
    loadTenderData() {
      if(!this.contractId)return;
      purchaseTenderService.queryByContractId({purchaseId:this.purchaseId}).then((data) => {
        if (data) {
          this.tenderForm = this.recover(this.tenderForm, data)
        }
      })
    },
    handleTabClick(tab) {
      // 如果点击的是付款标签页
      if (tab.paneName === 'payment') {
        // 刷新付款列表数据
        this.$nextTick(() => {
          if (this.$refs.paymentList) {
            this.$refs.paymentList.refreshList();
          }
        });
      }
    },
    getInfo() {
      contractService.getContractHeader({ id: this.contractId }).then(data => {
        this.detailData = data
      })
    },
    addBidder() {
      this.tenderForm.purchaseTenderFirmDTOList.push({
        company: {
          id: ''
        },
        contactPerson: '',
        contactPhone: '',
        delFlag: '0'
      })
    },
    returnToProjectDetails() {
      this.$router.push({
        path: '/purchase/PurchaseList',
        query: {
          id: this.projectId,
          basisType: this.basisType
        }
      })
    },
    removeBidder(row) {
      if (row.id) {
        row.delFlag = '1'
      } else {
        const index = this.tenderForm.purchaseTenderFirmDTOList.indexOf(row)
        this.tenderForm.purchaseTenderFirmDTOList.splice(index, 1)
      }
    },
    submitTenderForm() {
      this.$refs.tenderFormRef.validate((valid) => {
        if (valid) {
          this.tenderForm.contract.id = this.contractId
          purchaseTenderService.save(this.tenderForm).then((data) => {
            this.$message.success(data)
            this.loadTenderData()
            this.getInfo() // 重新加载数据
          })
        }
      })
    },
    handlePaymentDialogClosed() {
      this.paymentPlanData = []
      this.paymentEditMode = false
    },
    calculateRemainingAmount(row) {
      // 当本次付款金额输入框值变化时更新thisPlanAmount
      const mustAmount = parseFloat(row.mustAmount || 0);
      const thisPlanAmount = parseFloat(row.thisPlanAmount || 0);
      
      // 如果输入的金额大于应付金额，则限制为应付金额
      if (thisPlanAmount > mustAmount) {
        row.thisPlanAmount = mustAmount;
      }
    },
    calculateActualAmount(row) {
      // 计算采集付款金额 = 应付金额 - 本次付款金额
      const mustAmount = parseFloat(row.mustAmount || 0);
      const thisPlanAmount = parseFloat(row.thisPlanAmount || 0);
      let num = (mustAmount - thisPlanAmount).toFixed(2);
      return num < 0 ? 0 : num;
    },
    confirmPayment() {
      this.$confirm('确认进行付款操作?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        purchaseReceiptService.confirmPayment(this.paymentPlanData).then(res => {
          this.$message.success(res || '付款成功');
          this.paymentDialogVisible = false;
          
          // 刷新付款列表
          this.refreshPaymentList();
          this.loading = false;
        }).catch(() => {
          this.loading = false;
        });
      });
    },
    enablePaymentEdit() {
      this.paymentEditMode = true;
    },
    savePaymentChanges() {
      this.loading = true;
      purchaseReceiptService.paymentPlan(this.paymentPlanData).then(res => {
        this.$message.success(res || '付款计划已更新');
        this.paymentEditMode = false;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    cancelPaymentEdit() {
      this.paymentEditMode = false;
      // 重新加载数据
      this.loadPaymentPlanData();
    },
    exportPaymentPlan() {
      this.$message.success('付款计划导出功能正在开发中');
    },
    loadPaymentPlanData() {
      // 从服务器加载付款计划数据
      purchaseReceiptService.queryByContractId(this.contractId).then(res => {
        this.paymentPlanData = res;
      });
    },
    refreshPaymentList() {
      // 如果当前是付款标签页，直接刷新列表
      if (this.activeTab === 'payment' && this.$refs.paymentList) {
        this.$nextTick(() => {
          this.$refs.paymentList.refreshList();
        });
      }
    },
    showPaymentDialog() {
      this.loadPaymentPlanData();
      this.paymentDialogVisible = true;
    }
  }
}
</script>

<style lang="scss" scoped>
.none-sizing {
  padding: 0;
  margin: 0;
}
.purchase-details {
  padding: 20px;
  background: #fff;

  .header {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .title {
      font-size: 20px;
      // display: flex;
      // align-items: center;
      gap: 10px;
      .title-right {
        font-size: 16px;
      }

      .tags {
        display: flex;
        gap: 8px;
        margin-top: 10px;
      }
    }
  }

  .overview {
    background: #f5f7fa;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;
    display: flex;
    gap: 80px;

    .overview-item {
      // flex: 0 0 200px;

      .label {
        color: #5d7aab;
        margin-bottom: 8px;
        font-size: 14px;
      }

      .value {
        font-size: 18px;
        font-weight: 500;
        color: #192a4c;
      }
    }

    .amount-info {
      flex: 1;
      display: flex;
      gap: 80px;

      .amount-item {
        border-left: 1px solid #dcdfe6;
        padding-left: 20px;
        .label {
          color: #909399;
          margin-bottom: 8px;
        }

        .value {
          font-size: 18px;
          font-weight: 500;
          color: #192a4c;
        }
      }
    }
  }

  .tab-container {
    .tender-content {
      padding: 20px 0;

      .section {
        padding: 0 20px;
        margin-bottom: 30px;

        .section-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 15px;
        }

        .section-title {
          font-size: 16px;
          font-weight: 700;
          margin-bottom: 15px;
        }

        .upload-area {
          align-items: flex-start;

          .upload-box {
            flex: 1;
          }

          .date-picker {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-top: 15px;
          }
        }
      }
    }
  }

  .upload-demo {
    width: 100%;
  }

  .form-footer {
    text-align: center;
    margin-top: 20px;
    padding: 20px 0;
  }

  :deep(.el-form-item) {
    margin-bottom: 0;
  }

  .box-border {
    border: 1px solid #dcdfe6;
    padding: 40px !important;
    border-radius: 20px;
  }
}
.flex{
  display: flex;
}

.payment-header {
  margin-bottom: 15px;
  display: flex;
  justify-content: flex-end;
}

.payment-plan-dialog {
  .payment-title {
    text-align: center;
    margin-bottom: 20px;
    font-size: 18px;
    color: #303133;
  }
  
  .payment-actions {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 15px;
    
    .el-button {
      margin-left: 10px;
    }
  }
  
  .payment-footer {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    
    .el-button {
      margin: 0 10px;
    }
  }
}
</style>
